var app = getApp();

Page({
	data: {
		admin: app.globalData.domain,
		errImg: app.globalData.errimg,
		userInfo: {}
	},
	onLoad(options) {
		var that = this;
	},
	getUserInfo: function(e) {
		var that = this;
		//设置缓存
		wx.setStorage({
			key: "loginInformation",
			data: e.detail.userInfo
		})
		// 必须是在用户已经授权的情况下调用
		wx.getUserInfo({
			success: function(res) {
				wx.login({
					success: function(res2) {
						var code = res2.code;

						if (wx.getStorageSync('userInfo')) {
							that.login(code) //注册完成 调用登录
							return false;
						}

						app.globalAjax(
							'/api/wechat/register',
							"get", {
								code: code,
								encryptedData: res.encryptedData,
								iv: res.iv,
								rawData: res.rawData,
								signature: res.signature,
								sessionKey: wx.getStorageSync('sessionKey')
							},
							function(e) {
								if (e.code == 0) {
									that.login(code) //注册完成 调用登录
								} else {
									console.log('注册失败')
									console.log(e)
									that.login(code) //注册完成 调用登录
								}
							}
						);
					},
					fail: function(res) {
						console.log('login.js line71', res)
					}
				})
			}
		})
	},
	login: function(code) { //第一次登录
		var that = this;
		app.globalAjax(
			'/api/wechat/login',
			"get", {
				code: code
			},
			function(e) {
				if (e.code == 0) {
					wx.setStorage({
						key: "token",
						data: e.token //需要存储的数据
					})
					wx.setStorage({
						key: "userInfo",
						data: e.userInfo //需要存储的数据
					});

					that.setData({
						userInfo: e.userInfo
					});
					
					that.setUserDealer(e.userInfo.userId)
				}
			}
		);
	},
	setUserDealer(userId){
		var dealer = wx.getStorageSync('dealer')
		var storeId = dealer.id
		app.globalAjax(
			'/api/wechat/chooseStore',
			"get", {
				userId: userId,
				storeId: storeId
			},
			function(e) {
				wx.reLaunch({
					url: '/pages/index/index'
				})
			}
		);
	},
	onShow: function() {
		let vm = this;
	},
	applyGroup: function(event){ //若附近三公里没有团，跳转申请当团长
		wx.navigateTo({
			url: '/pages/member/group/group'
		})
	}
})
